using System.Text.RegularExpressions;
using System.Web;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using Publicuse.Entity;
using Geekeradmin.Entitys;

namespace Geekeradmin.Filters
{
  /// <summary>
  /// 结果过滤器
  /// 执行步骤：构造函数》Action方法》OnResultExecuting》开始渲染视图》OnResultExecuting
  /// </summary>
  public class CustomResult : Attribute, IResultFilter
  {
    private readonly ILogger<CustomResult> logger;

    public CustomResult(ILogger<CustomResult> logger)
    {
      this.logger = logger;
    }

    public void OnResultExecuting(ResultExecutingContext context)
    {
      Console.WriteLine("OnResultExecuting...");
      if (context.Result is JsonResult)
      {
        JsonResult result = (JsonResult)context.Result;
        CommonResult commonResult = new CommonResult();
        commonResult = (CommonResult)result.Value;
        if (!string.IsNullOrEmpty(commonResult.msg) && commonResult.code != 3000)
        {
          bool containsDigit = Regex.IsMatch(commonResult.msg, @"\d+");
          bool containsLetter = Regex.IsMatch(commonResult.msg, @"[a-zA-Z]");
          if (containsLetter && !containsDigit)
          {
            commonResult.msg = ImplementResult.WorkErr.GetRemark();
          }
        }
        var resultb = new CommonResult()
        {
          stTime = commonResult.stTime,
          msg = commonResult.msg,
          data = commonResult.data,
          code = commonResult.code,
          count = commonResult.count,
          datab = commonResult.datab,
          datac = commonResult.datac,
          etTime = commonResult.etTime,
          timeconsuming = commonResult.timeconsuming,
        };
        context.Result = new JsonResult(resultb);
      }
    }

    public void OnResultExecuted(ResultExecutedContext context)
    {
      Console.WriteLine("OnResultExecuted...");
    }
  }
}
